import React, {PropTypes} from "react";
import {connect} from "react-redux";
import {fetchPosts, reset} from "../../actions";
import {Link} from "react-router";
import Swiper from "react-id-swiper";
import Events from "../../utils/Events";
import isEqual from "lodash/isEqual";
import cookie from "react-cookie";
import SubCategory from "../../components/SubCategory";
import RecommendTitle from "../../components/RecommendTitle";
import Goods from "../../components/Goods";
import MallMenu from "../../components/MallMenu";

class mallIndex extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            pageindex: 1,
            isLoading: true,
            pCategoryList: [],
            subCategoryList: [],
            bannerList: [],
            listItem: [],
            categoryCode: 0,
            categoryIndex: 0,
            shoppingCartCount: 0,
            firstRequest: false
        }
    }

    componentWillMount() {
        document.title = "商城首页";
        this.setState({categoryCode : cookie.load('categoryCode') || 0});
    }

    componentDidMount() {
        const query = this.props.location.query;
        const isFromApp = cookie.load("isFromApp");
        const isBaoXiang = cookie.load("isBaoXiang");

        if (!query.isFromApp && (!isFromApp || isFromApp == 0)) {
            if (process.env.NODE_ENV === 'production') {
                if (query.token) {
                    cookie.save("token", query.token);
                    cookie.save("userName", query.userName);
                }
            } else {
                cookie.save("token", "4eed7fc046d2411b9263029b3dbcf23e");
            }
            cookie.save("isFromApp", 0); //0: weixin, 1: app
            if(query.isBaoXiang){
                cookie.save("isBaoXiang", 1);
            }
        } else {
            if (query.isFromApp) {
                cookie.save("isFromApp", query.isFromApp);
            }
        }

        const header = {"X-Client-ID": "123456"}

        let pageindex = this.state.pageindex,
            categoryCode = this.state.categoryCode,
            params;
        if (categoryCode != 0) {
            params = {categoryCode: categoryCode, pageindex: pageindex, pagesize: 10};
        } else {
            params = {pageindex: pageindex, pagesize: 10};
        }
        this.props.dispatch(reset("mainPageData"))
        this.props.dispatch(fetchPosts("mainPageData", header, params))
        this._scrollListener = Events.on(window, 'scroll', this.checkButtom.bind(this));
        if (window.lubobo) {
            window.lubobo.clearHistory();
        }
    }

    componentWillUnmount() {
        this._scrollListener && this._scrollListener.off();
    }

    addList(lists) {
        this.setState({isLoading: lists.length == 10 ? true : false});
        if (this.state.pageindex == 1) {
            this.setState({listItems: lists});
        } else {
            this.setState({listItems: this.state.listItems.concat(lists)});
        }
    }

    checkButtom() {
        if(this.state.firstRequest) {
            const header = {"X-Client-ID": "123456"}
            let scrollTop = document.body.scrollTop,
                innerHeight = window.innerHeight,
                scrollHeight = document.body.scrollHeight,
                pageindex = this.state.pageindex,
                categoryCode = this.state.categoryCode;

            if (scrollTop + innerHeight >= scrollHeight && this.state.isLoading) {
                pageindex++;
                this.setState({pageindex: pageindex});
                let params;
                if (categoryCode != 0) {
                    params = {categoryCode: categoryCode, pageindex: pageindex, pagesize: 10};
                } else {
                    params = {pageindex: pageindex, pagesize: 10};
                }
                this.props.dispatch(reset("mainPageDataByPage"));
                this.props.dispatch(fetchPosts("mainPageDataByPage", header, params));
            }
        }
    }

    categoryPageData(categoryCode, index) {
        this.setState({pageindex: 1});
        this.setState({categoryCode: categoryCode});
        this.setState({categoryIndex: index});
        const header = {"X-Client-ID": "123456"}
        cookie.save('categoryCode', categoryCode);
        this.props.dispatch(reset("mainPageData"));
        this.props.dispatch(fetchPosts("mainPageData", header, {
            "categoryCode": categoryCode,
            "pageindex": this.state.pageindex,
            "pagesize": 10
        }))
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.MainPageData.errorCode === 0) {
            this.setState({
                loading: false
            })
        }
        // 刷新购物车数量
        let shoppingCartCount = 0;
        let shoppingCarItemList = cookie.load("shoppingCarItemList") || [];
        shoppingCarItemList.map((item) => {
            shoppingCartCount += item.buyNumber;
        });
        if (nextProps.MainPageData.errorCode === 0 && !isEqual(nextProps.MainPageData, this.props.MainPageData)) {
            if(nextProps.MainPageData.data.categoryGoodsVos) {
                this.addList(nextProps.MainPageData.data.categoryGoodsVos);
                this.setState({
                    pCategoryList: nextProps.MainPageData.data.goodsCategoryForFirstLevelVos,
                    subCategoryList: nextProps.MainPageData.data.goodsCategoryForSecondLevelVos,
                    bannerList: nextProps.MainPageData.data.categoryBannerVos,
                    shoppingCartCount: shoppingCartCount
                });
                this.setState({firstRequest: true});
            }
        }
        if (nextProps.RecommendGoodsList.errorCode === 0 && !isEqual(nextProps.RecommendGoodsList, this.props.RecommendGoodsList)) {
            if(nextProps.RecommendGoodsList.data.categoryGoodsVos) {
                this.addList(nextProps.RecommendGoodsList.data.categoryGoodsVos);
            }
        }
    }

    renderBanner() {
        if (this.state.bannerList.length > 0) {
            const params = {
                pagination: '.swiper-pagination',
                paginationClickable: true,
                loop: true,
                autoplay: 5000
            };
            return (
                <Swiper {...params} >
                    {this.state.bannerList.map((item, index) => {
                        return (
                            <div key={index}>
                                <a href={item.url.trim().length == 0 ? "javascript:return false;" : item.url}>
                                    <img src={item.imagePath}/>
                                </a>
                            </div>
                        );
                    })
                    }
                </Swiper>
            );
        }
    }

    renderRecommendTitle() {
        if (this.state.categoryIndex != 0) {
            return (
                <RecommendTitle/>
            );
        }
    }

    render() {
        if (this.state.loading) {
            return (<div className="loading"><span>loading</span></div>)
        } else {
            let categoryWidth = this.state.pCategoryList.length * 80 + 'px';
            return (
                <div >
                    {/*搜索*/}
                    <div className="mall-main-search">
                        <Link to={`mall/searchGoods`}>
                            <div>
                                <img src="http://oeb6w1s1c.bkt.clouddn.com/170510165015932477026341.png"/>
                                <input type="text" value="搜索好物" readOnly="true"/>
                            </div>
                        </Link>
                    </div>

                    {/*分类*/}
                    <div className="mall-category-bar-outer">
                        <div className="mall-category-bar" style={{width: categoryWidth}}>
                            {this.state.pCategoryList.map((item, index) => {
                                let className = ((index == 0 && this.state.categoryCode == 0) || item.categoryCode == this.state.categoryCode) ? 'curr' : '';
                                return (
                                    <Link className={className} key={index}
                                          onClick={this.categoryPageData.bind(this, item.categoryCode, index)}>{item.categoryName}</Link>
                                );
                            })}
                        </div>
                    </div>

                    {/*banner*/}
                    {this.renderBanner()}


                    {/*子分类*/}
                    <div className="mall-subcategory">
                        <ul>
                            {this.state.subCategoryList.map((item, index) => {
                                return (
                                    <SubCategory key={index} category={item}/>
                                );
                            })}
                        </ul>
                    </div>

                    {/*推荐商品*/}
                    <RecommendTitle/>
                    <div className="mall-goods-list">
                        <ul>
                            {this.state.listItems.map((item, index) => {
                                    return (
                                        <Goods key={index} item={item}/>
                                    )
                                }
                            )}
                        </ul>
                    </div>

                    {/*菜单*/}
                    <MallMenu clickIndex="0" shoppingCartCount={this.state.shoppingCartCount}/>

                </div>
            )
        }
    }
}
mallIndex.propTypes = {
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
}
mallIndex.contextTypes = {
    router: React.PropTypes.object
}
function mapStateToProps(state) {
    const {postsByApi} = state
    const {
        isFetching,
        items: MainPageData
    } = postsByApi["mainPageData"] || {
        isFetching: false,
        items: {}
    }
    const {
        items: RecommendGoodsList
    } = postsByApi["mainPageDataByPage"] || {
        items: {}
    }

    return {
        MainPageData,
        isFetching,
        RecommendGoodsList
    }
}


export default connect(mapStateToProps)(mallIndex);

